package com.example.foods.controller;

import com.example.foods.domain.AjaxResult;
import com.example.foods.domain.CategoryInfo;
import com.example.foods.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/cat")
@Slf4j //该注解可以帮助在当前类内部添加一个名为log的变量，且该变量引用了日志记录器对象
public class CategoryController {

    @Resource
    private CategoryService categoryService;

    @PostMapping("/checkCatName")
    public AjaxResult checkCatName(String catName) {
        log.debug("catName=" + catName);
        CategoryInfo categoryInfo = this.categoryService.findByCatName(catName);
        return AjaxResult.ok(categoryInfo == null);
    }

    @PostMapping("/add")
    public AjaxResult addCategory(@RequestBody @Valid CategoryInfo categoryInfo, BindingResult bindingResult) {
        if (bindingResult.hasFieldErrors()) {
            return AjaxResult.error(-1, "无效请求!");
        }
        try {
            boolean result = this.categoryService.addCategory(categoryInfo);
            return AjaxResult.ok(result);
        } catch (Exception e) {
            return AjaxResult.error(-1, e.getMessage());
        }
    }

    @GetMapping("/list")
    public AjaxResult listCategory() {
        List<CategoryInfo> categoryInfoList = this.categoryService.findAllCategories();
        return AjaxResult.ok(categoryInfoList);
    }

    @PostMapping("/delete")
    public AjaxResult deleteCategories(Integer[] catId) {
        log.debug("要删除的类别的编号:" + Arrays.toString(catId));
        if (catId == null || catId.length == 0) {
            return AjaxResult.ok(0);
        }
        int count = this.categoryService.deleteCategories(catId);
        return AjaxResult.ok(count);
    }
}
